<template>
  <j-modal :title="title" :width="520" :visible="visible" :footer="null" @cancel="handleCancel" cancelText="关闭">
    <div class="qr-wrap">
      <QrCode :value="qrUrl" :width="240" ref="qrRef" @done="onQrDone" />
      <div class="link-box">
        <a-input v-model:value="qrUrl" readonly />
        <a-space>
<!--          <a-button size="small" @click="copyUrl">复制链接</a-button>-->
          <a-button type="primary" size="small" @click="downloadQr">下载二维码</a-button>
        </a-space>
      </div>
    </div>
  </j-modal>
</template>

<script lang="ts" setup>
  import { ref, defineExpose } from 'vue'
  import JModal from '/@/components/Modal/src/JModal/JModal.vue'
  import QrCode from '/@/components/Qrcode/src/Qrcode.vue'
  import { useMessage } from '/@/hooks/web/useMessage'

  const { createMessage } = useMessage()
  const title = ref('生成二维码')
  const visible = ref(false)
  const qrUrl = ref('')
  const qrRef = ref<any>(null)

  // 钉钉唤起Url（path 需 encode）
  const BASE_URL = 'https://applink.dingtalk.com/page/h5_app_open'
  const APP_ID = '3954441815'
  const CORP_ID = 'ding60ca55316ff60640f5bf40eda33b7ba0'
  const APP_TYPE = '2'

  function buildUrl(period: string) {
    const pathRaw = `/index.html?period=${period}`
    const pathEncoded = encodeURIComponent(pathRaw)
    return `${BASE_URL}?appId=${APP_ID}&corpId=${CORP_ID}&appType=${APP_TYPE}&path=${pathEncoded}`
  }

  function open(record: Recordable) {
    const period = record?.period
    if (!period) {
      createMessage.warning('缺少期数')
      return
    }
    qrUrl.value = buildUrl(period)
    visible.value = true
  }

  function handleCancel() {
    visible.value = false
  }

  function copyUrl() {
      navigator.clipboard?.writeText(qrUrl.value).then(() => {
      createMessage.success('已复制链接')
    })
  }

  function downloadQr() {
    qrRef.value?.download?.('二维码.png')
  }

  function onQrDone() {}

  defineExpose({ open })
</script>

<style lang="less" scoped>
  .qr-wrap {
    display: flex;
    gap: 16px;
    align-items: center;
  }
  .link-box {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
</style>
